using System;
using System.Data;
using System.Configuration;
using CodeWork.Library.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Data.SqlTypes;
using CodeWork.Library;
using System.Text;
using System.Data.SqlClient;

/// <summary>
/// ORM object that maps to tbl_SaleOrder
/// </summary>
namespace EasyCommerce.DAL
{
    public class SaleOrder : SqlServerDAO
    {
        /// <summary>
        /// Self table parameters
        /// </summary>
        private int _id;
		private int _orderedBySiteuserId;
		private int _itemProductId;
		private int _itemQuantity;
		private double _totalPrice;
		private double _giftCouponUseAmount;
		private double _tax;
		private double _shippingCost;
		private double _finalAmount;
		private bool _isPaymentClear;
		private string _trackingNumber;
		private string _orderStatus;

        /// <summary>
        /// Foriegn key parameters
        /// </summary>
        private List<DiscountCouponAndSalesOrder> _usedDiscountCouponAndSalesOrder;
		private bool _isUsedDiscountCouponAndSalesOrderLoaded;
		

        /// <summary>
        /// Self table properties
        /// </summary>
		public int Id
		{
			get { return this._id; }
			set { this._id = value; }
		}

		public int OrderedBySiteuserId
		{
			get { return this._orderedBySiteuserId; }
			set { this._orderedBySiteuserId = value; }
		}

		public int ItemProductId
		{
			get { return this._itemProductId; }
			set { this._itemProductId = value; }
		}

		public int ItemQuantity
		{
			get { return this._itemQuantity; }
			set { this._itemQuantity = value; }
		}

		public double TotalPrice
		{
			get { return this._totalPrice; }
			set { this._totalPrice = value; }
		}

		public double GiftCouponUseAmount
		{
			get { return this._giftCouponUseAmount; }
			set { this._giftCouponUseAmount = value; }
		}

		public double Tax
		{
			get { return this._tax; }
			set { this._tax = value; }
		}

		public double ShippingCost
		{
			get { return this._shippingCost; }
			set { this._shippingCost = value; }
		}

		public double FinalAmount
		{
			get { return this._finalAmount; }
			set { this._finalAmount = value; }
		}

		public bool IsPaymentClear
		{
			get { return this._isPaymentClear; }
			set { this._isPaymentClear = value; }
		}

		public string TrackingNumber
		{
			get { return this._trackingNumber; }
			set { this._trackingNumber = value; }
		}

		public string OrderStatus
		{
			get { return this._orderStatus; }
			set { this._orderStatus = value; }
		}
		
        /// <summary>
        /// Foreign key properties, loaded on demand only
        /// </summary>
        public List<DiscountCouponAndSalesOrder> UsedDiscountCouponAndSalesOrder
		{
			get
			{
				if (!this._isUsedDiscountCouponAndSalesOrderLoaded)
				{
					List<Condition> conditions = new List<Condition>();
					conditions.Add(new Condition("used_by_saleorder_id", ConditionOperator.Equal,this._id, JoinOperator.FirstValue));
					DiscountCouponAndSalesOrder discountCouponAndSalesOrder = new DiscountCouponAndSalesOrder();
					this._usedDiscountCouponAndSalesOrder = discountCouponAndSalesOrder.Load(conditions);
					this._isUsedDiscountCouponAndSalesOrderLoaded = true;
				}
				return this._usedDiscountCouponAndSalesOrder;
			}
			set
			{
				this._usedDiscountCouponAndSalesOrder = value;
				this._isUsedDiscountCouponAndSalesOrderLoaded = true;
			}
		}
		

        /// <summary>
        /// Empty Constructor
        /// </summary>
        public SaleOrder() { }

        /// <summary>
        /// Parameterized constructor
        /// </summary>
        /// <param name="id"></param>
		/// <param name="orderedBySiteuserId"></param>
		/// <param name="itemProductId"></param>
		/// <param name="itemQuantity"></param>
		/// <param name="totalPrice"></param>
		/// <param name="giftCouponUseAmount"></param>
		/// <param name="tax"></param>
		/// <param name="shippingCost"></param>
		/// <param name="finalAmount"></param>
		/// <param name="isPaymentClear"></param>
		/// <param name="trackingNumber"></param>
		/// <param name="orderStatus"></param>
        public SaleOrder
        (
            int id,
			int orderedBySiteuserId,
			int itemProductId,
			int itemQuantity,
			double totalPrice,
			double giftCouponUseAmount,
			double tax,
			double shippingCost,
			double finalAmount,
			bool isPaymentClear,
			string trackingNumber,
			string orderStatus
        )
        {
            this._id = id;
			this._orderedBySiteuserId = orderedBySiteuserId;
			this._itemProductId = itemProductId;
			this._itemQuantity = itemQuantity;
			this._totalPrice = totalPrice;
			this._giftCouponUseAmount = giftCouponUseAmount;
			this._tax = tax;
			this._shippingCost = shippingCost;
			this._finalAmount = finalAmount;
			this._isPaymentClear = isPaymentClear;
			this._trackingNumber = trackingNumber;
			this._orderStatus = orderStatus;
        }

        /// <summary>
        /// Static save method. Saves the current instance in the table using the provided values using the
        /// primary key id. Expects that the Id is a primary key of an existing record in table.
        /// </summary>
        /// <param name="id"></param>
		/// <param name="orderedBySiteuserId"></param>
		/// <param name="itemProductId"></param>
		/// <param name="itemQuantity"></param>
		/// <param name="totalPrice"></param>
		/// <param name="giftCouponUseAmount"></param>
		/// <param name="tax"></param>
		/// <param name="shippingCost"></param>
		/// <param name="finalAmount"></param>
		/// <param name="isPaymentClear"></param>
		/// <param name="trackingNumber"></param>
		/// <param name="orderStatus"></param>
        /// <returns>Boolean result as success or failure</returns>
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool Save
        (
            int id,
			int orderedBySiteuserId,
			int itemProductId,
			int itemQuantity,
			double totalPrice,
			double giftCouponUseAmount,
			double tax,
			double shippingCost,
			double finalAmount,
			bool isPaymentClear,
			string trackingNumber,
			string orderStatus
        )
        {
            SaleOrder saleOrder = new SaleOrder();
            saleOrder.Id = id;
			saleOrder.OrderedBySiteuserId = orderedBySiteuserId;
			saleOrder.ItemProductId = itemProductId;
			saleOrder.ItemQuantity = itemQuantity;
			saleOrder.TotalPrice = totalPrice;
			saleOrder.GiftCouponUseAmount = giftCouponUseAmount;
			saleOrder.Tax = tax;
			saleOrder.ShippingCost = shippingCost;
			saleOrder.FinalAmount = finalAmount;
			saleOrder.IsPaymentClear = isPaymentClear;
			saleOrder.TrackingNumber = trackingNumber;
			saleOrder.OrderStatus = orderStatus;

            return saleOrder.Save();
        }

        /// <summary>
        /// Saves the current instance and returns result
        /// </summary>
        /// <returns>Boolean result as success or failure</returns>
        public override bool Save()
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddCommandParameter(command, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, Id);
			AddCommandParameter(command, "@OrderedBySiteuserId", SqlDbType.Int, 0, ParameterDirection.Input, OrderedBySiteuserId);
			AddCommandParameter(command, "@ItemProductId", SqlDbType.Int, 0, ParameterDirection.Input, ItemProductId);
			AddCommandParameter(command, "@ItemQuantity", SqlDbType.Int, 0, ParameterDirection.Input, ItemQuantity);
			AddCommandParameter(command, "@TotalPrice", SqlDbType.Decimal, 0, ParameterDirection.Input, TotalPrice);
			AddCommandParameter(command, "@GiftCouponUseAmount", SqlDbType.Decimal, 0, ParameterDirection.Input, GiftCouponUseAmount);
			AddCommandParameter(command, "@Tax", SqlDbType.Decimal, 0, ParameterDirection.Input, Tax);
			AddCommandParameter(command, "@ShippingCost", SqlDbType.Decimal, 0, ParameterDirection.Input, ShippingCost);
			AddCommandParameter(command, "@FinalAmount", SqlDbType.Decimal, 0, ParameterDirection.Input, FinalAmount);
			AddCommandParameter(command, "@IsPaymentClear", SqlDbType.Bit, 0, ParameterDirection.Input, IsPaymentClear);
			AddCommandParameter(command, "@TrackingNumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, TrackingNumber);
			AddCommandParameter(command, "@OrderStatus", SqlDbType.NVarChar, 250, ParameterDirection.Input, OrderStatus);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_Save.ToString());

            int returnValue = (int)GetOneData(command);
            return (returnValue == 0 ? false : true);
        }

        /// <summary>
        /// Saves the current instance based on provided conditions. This method assumes that
        /// conditions are provided in correct order and in proper format.
        /// </summary>
        /// <param name="conditions">Custom condition based on which to match data</param>
        /// <returns>Boolean result as success or failure</returns>
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public bool Save(List<Condition> conditions)
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            PrepareConditionalParameters(command, conditions);

            AddCommandParameter(command, "@NewOrderedBySiteuserId", SqlDbType.Int, 0, ParameterDirection.Input, OrderedBySiteuserId);
			AddCommandParameter(command, "@NewItemProductId", SqlDbType.Int, 0, ParameterDirection.Input, ItemProductId);
			AddCommandParameter(command, "@NewItemQuantity", SqlDbType.Int, 0, ParameterDirection.Input, ItemQuantity);
			AddCommandParameter(command, "@NewTotalPrice", SqlDbType.Decimal, 0, ParameterDirection.Input, TotalPrice);
			AddCommandParameter(command, "@NewGiftCouponUseAmount", SqlDbType.Decimal, 0, ParameterDirection.Input, GiftCouponUseAmount);
			AddCommandParameter(command, "@NewTax", SqlDbType.Decimal, 0, ParameterDirection.Input, Tax);
			AddCommandParameter(command, "@NewShippingCost", SqlDbType.Decimal, 0, ParameterDirection.Input, ShippingCost);
			AddCommandParameter(command, "@NewFinalAmount", SqlDbType.Decimal, 0, ParameterDirection.Input, FinalAmount);
			AddCommandParameter(command, "@NewIsPaymentClear", SqlDbType.Bit, 0, ParameterDirection.Input, IsPaymentClear);
			AddCommandParameter(command, "@NewTrackingNumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, TrackingNumber);
			AddCommandParameter(command, "@NewOrderStatus", SqlDbType.NVarChar, 250, ParameterDirection.Input, OrderStatus);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_SaveConditional.ToString());

            int returnValue = (int)GetOneData(command);
            return (returnValue == 0 ? false : true);
        }

        /// <summary>
        /// Static creational method. This method actually adds a new entry in the table with
        /// the provided information.
        /// </summary>
        /// <param name="orderedBySiteuserId"></param>
		/// <param name="itemProductId"></param>
		/// <param name="itemQuantity"></param>
		/// <param name="totalPrice"></param>
		/// <param name="giftCouponUseAmount"></param>
		/// <param name="tax"></param>
		/// <param name="shippingCost"></param>
		/// <param name="finalAmount"></param>
		/// <param name="isPaymentClear"></param>
		/// <param name="trackingNumber"></param>
		/// <param name="orderStatus"></param>
        /// <returns>Instance of the created object</returns>
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static SaleOrder Create
        (
            int orderedBySiteuserId,
			int itemProductId,
			int itemQuantity,
			double totalPrice,
			double giftCouponUseAmount,
			double tax,
			double shippingCost,
			double finalAmount,
			bool isPaymentClear,
			string trackingNumber,
			string orderStatus
        )
        {
            SaleOrder saleOrder = new SaleOrder();
            saleOrder.OrderedBySiteuserId = orderedBySiteuserId;
			saleOrder.ItemProductId = itemProductId;
			saleOrder.ItemQuantity = itemQuantity;
			saleOrder.TotalPrice = totalPrice;
			saleOrder.GiftCouponUseAmount = giftCouponUseAmount;
			saleOrder.Tax = tax;
			saleOrder.ShippingCost = shippingCost;
			saleOrder.FinalAmount = finalAmount;
			saleOrder.IsPaymentClear = isPaymentClear;
			saleOrder.TrackingNumber = trackingNumber;
			saleOrder.OrderStatus = orderStatus;

            return (saleOrder.Create() ? saleOrder : null);
        }

        /// <summary>
        /// Instance creational method. Inserts the current object as a new entry in table.
        /// </summary>
        /// <returns>Boolean result as success or failure</returns>
        public override bool Create()
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddCommandParameter(command, "@OrderedBySiteuserId", SqlDbType.Int, 0, ParameterDirection.Input, OrderedBySiteuserId);
			AddCommandParameter(command, "@ItemProductId", SqlDbType.Int, 0, ParameterDirection.Input, ItemProductId);
			AddCommandParameter(command, "@ItemQuantity", SqlDbType.Int, 0, ParameterDirection.Input, ItemQuantity);
			AddCommandParameter(command, "@TotalPrice", SqlDbType.Decimal, 0, ParameterDirection.Input, TotalPrice);
			AddCommandParameter(command, "@GiftCouponUseAmount", SqlDbType.Decimal, 0, ParameterDirection.Input, GiftCouponUseAmount);
			AddCommandParameter(command, "@Tax", SqlDbType.Decimal, 0, ParameterDirection.Input, Tax);
			AddCommandParameter(command, "@ShippingCost", SqlDbType.Decimal, 0, ParameterDirection.Input, ShippingCost);
			AddCommandParameter(command, "@FinalAmount", SqlDbType.Decimal, 0, ParameterDirection.Input, FinalAmount);
			AddCommandParameter(command, "@IsPaymentClear", SqlDbType.Bit, 0, ParameterDirection.Input, IsPaymentClear);
			AddCommandParameter(command, "@TrackingNumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, TrackingNumber);
			AddCommandParameter(command, "@OrderStatus", SqlDbType.NVarChar, 250, ParameterDirection.Input, OrderStatus);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_Create.ToString());

            Id = (int)GetOneData(command);
            return (Id == 0 ? false : true);
        }

        /// <summary>
        /// Static deletion method. Deletes a record from table using the provided primary key id.
        /// </summary>
        /// <param name="id">Primary key</param>
        /// <returns>Boolean result as success or failure</returns>
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Delete, true)]
        public static bool Delete(int id)
        {
            SaleOrder saleOrder = new SaleOrder();
            saleOrder.Id = id;

            return saleOrder.Delete();
        }

        /// <summary>
        /// Static deletion method. Deletes a list record from table using the provided primary keys id.
        /// </summary>
        /// <param name="ids">List of primarky key id</param>
        /// <returns>Boolean result as success or failure</returns>
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Delete, true)]
        public static bool Delete(List<int> ids)
        {
            string csvIds = Utility.MakeCSV(ids);

            SaleOrder saleOrder = new SaleOrder();

            return saleOrder.Delete(csvIds);
        }

        /// <summary>
        /// Static deletion method. Deletes records from table using provided conditions.
        /// </summary>
        /// <param name="conditions">Custom condition based on which to match data</param>
        /// <returns>Boolean result as success or failure</returns>
        public static bool Delete(List<Condition> conditions)
        {
            SaleOrder saleOrder = new SaleOrder();

            return saleOrder.ConditionalDelete(conditions);
        }

        /// <summary>
        /// This is helper method for conditional delete method above. Not for other general use.
        /// </summary>
        /// <param name="conditions">Custom condition based on which to match data</param>
        /// <returns>Boolean result as success or failure</returns>
        private bool ConditionalDelete(List<Condition> conditions)
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            PrepareConditionalParameters(command, conditions);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_DeleteConditional.ToString());

            int returnValue = (int)GetOneData(command);
            return (returnValue == 0 ? false : true);
        }

        /// <summary>
        /// This is a helper method for multiple id delete method. Not for general use.
        /// </summary>
        /// <param name="csvIds">Comma seperated primary key values as string</param>
        /// <returns>Boolean result as success or failure</returns>
        private bool Delete(string csvIds)
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddCommandParameter(command, "@Ids", SqlDbType.NVarChar, 500, ParameterDirection.Input, csvIds);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_DeleteMultiple.ToString());

            int returnValue = (int)GetOneData(command);
            return (returnValue == 0 ? false : true);
        }

        /// <summary>
        /// Instance deletion method. Deletes the current instance from table.
        /// </summary>
        /// <returns>Boolean result as success or failure</returns>
        public override bool Delete()
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddCommandParameter(command, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, Id);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_DeleteOne.ToString());

            int returnValue = (int)GetOneData(command);
            return (returnValue == 0 ? false : true);
        }

        /// <summary>
        /// Static selection method. Used for loading a perticular data using primary key id.
        /// </summary>
        /// <param name="id">Primary key</param>
        /// <returns>Instance of the loaded object</returns>
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static SaleOrder Load(int id)
        {
            SaleOrder saleOrder = new SaleOrder();
            saleOrder.Id = id;

            if (saleOrder.Load())
                return saleOrder;
            else
                return null;
        }

        /// <summary>
        /// Instance selection method that fetches data using paging and sorting and also with 
        /// custom conditions.
        /// </summary>
        /// <param name="oderBy">Sorting order</param>
        /// <param name="startRow">Page start position</param>
        /// <param name="pageSize">Number of maximum record to be shown</param>
        /// <param name="conditions">Custom condition based on which to match data</param>
        /// <returns>List of instances of loaded objects</returns>
        public List<SaleOrder> Load(string orderBy, int startRow, int pageSize, List<Condition> conditions)
        {
            List<SaleOrder> saleOrders = new List<SaleOrder>();
			
			SqlCommand command = (SqlCommand)CreateCommand();
			
            PrepareConditionalParameters(command, conditions);

            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddCommandParameter(command, "@OrderBy", SqlDbType.NVarChar, 50, ParameterDirection.Input, orderBy);
            AddCommandParameter(command, "@StartRow", SqlDbType.Int, 0, ParameterDirection.Input, startRow);
            AddCommandParameter(command, "@PageSize", SqlDbType.Int, 0, ParameterDirection.Input, pageSize);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_LoadConditionalPaged.ToString());

            List<BaseDAO> dataList = GetListData(command);

            foreach (BaseDAO data in dataList)
            {
                SaleOrder saleOrder = (SaleOrder)data;
                saleOrders.Add(saleOrder);
            }

            return saleOrders;
        }

        /// <summary>
        /// Counts the number of total record available
        /// </summary>
        /// <param name="conditions">Custom condition based on which to match data</param>
        /// <returns>Count of the records</returns>
        public int LoadCount(List<Condition> conditions)
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            PrepareConditionalParameters(command, conditions);

            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_LoadConditionalPagedCount.ToString());

            int returnValue = (int)GetOneData(command);
            return returnValue;
        }

        /// <summary>
        /// Instance selection method that fetches data using paging and sorting.
        /// </summary>
        /// <param name="oderBy">Sorting order</param>
        /// <param name="startRow">Page start position</param>
        /// <param name="pageSize">Number of maximum record to be shown</param>
        /// <returns>List of instances of loaded objects</returns>
        public List<SaleOrder> Load(string orderBy, int startRow, int pageSize)
        {
            List<SaleOrder> saleOrders = new List<SaleOrder>();
            
			SqlCommand command = (SqlCommand)CreateCommand();
			
            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddCommandParameter(command, "@OrderBy", SqlDbType.NVarChar, 50, ParameterDirection.Input, orderBy);
            AddCommandParameter(command, "@StartRow", SqlDbType.Int, 0, ParameterDirection.Input, startRow);
            AddCommandParameter(command, "@PageSize", SqlDbType.Int, 0, ParameterDirection.Input, pageSize);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_LoadPaged.ToString());

            List<BaseDAO> dataList = GetListData(command);

            foreach (BaseDAO data in dataList)
            {
                SaleOrder saleOrder = (SaleOrder)data;
                saleOrders.Add(saleOrder);
            }

            return saleOrders;
        }

        /// <summary>
        /// Counts the number of total record available
        /// </summary>
        /// <returns>Count of the records</returns>
        public int LoadCount()
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_LoadPagedCount.ToString());

            int returnValue = (int)GetOneData(command);
            return returnValue;
        }

        /// <summary>
        /// Instance selection method. Used for reloading the current object from table. This method uses
        /// the Id of the current object to load and expects that the Id is correct.
        /// </summary>
        /// <returns>Boolean result as success or failure</returns>
        public override bool Load()
        {
			SqlCommand command = (SqlCommand)CreateCommand();
			
            AddCommandParameter(command, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddCommandParameter(command, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, Id);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_Load.ToString());

            List<BaseDAO> dataList = GetListData(command);

            foreach (BaseDAO data in dataList)
            {
                SaleOrder saleOrder = (SaleOrder)data;

                this._id = saleOrder._id;
				this._orderedBySiteuserId = saleOrder._orderedBySiteuserId;
				this._itemProductId = saleOrder._itemProductId;
				this._itemQuantity = saleOrder._itemQuantity;
				this._totalPrice = saleOrder._totalPrice;
				this._giftCouponUseAmount = saleOrder._giftCouponUseAmount;
				this._tax = saleOrder._tax;
				this._shippingCost = saleOrder._shippingCost;
				this._finalAmount = saleOrder._finalAmount;
				this._isPaymentClear = saleOrder._isPaymentClear;
				this._trackingNumber = saleOrder._trackingNumber;
				this._orderStatus = saleOrder._orderStatus;

                break;
            }

            return (dataList.Count > 0 ? true : false);
        }

        /// <summary>
        /// Instance selection method. Used for loading multiple record based on provided conditions.
        /// </summary>
        /// <param name="conditions">Custom condition based on which to match data</param>
        /// <returns>List of instances of loaded objects</returns>
        public List<SaleOrder> Load(List<Condition> conditions)
        {
            List<SaleOrder> saleOrders = new List<SaleOrder>();

			SqlCommand command = (SqlCommand)CreateCommand();
			
            PrepareConditionalParameters(command, conditions);

            SetCommandType(command, CommandType.StoredProcedure, StoreProcedureName.Sp_SaleOrder_LoadConditional.ToString());

            List<BaseDAO> dataList = GetListData(command);

            foreach (BaseDAO data in dataList)
            {
                SaleOrder saleOrder = (SaleOrder)data;
                saleOrders.Add(saleOrder);
            }

            return saleOrders;
        }

        /// <summary>
        /// Prepares the conditional parameters for use with Create/ Save/ Load/ Delete methods
        /// that use custom condition. Prepares the user Command object for using conditions.
        /// </summary>
        /// <param name="conditions">Custom condition based on which to match data</param>
        private void PrepareConditionalParameters(SqlCommand command, List<Condition> conditions)
        {
            StringBuilder condition = new StringBuilder();

            object id = null;
			object orderedBySiteuserId = null;
			object itemProductId = null;
			object itemQuantity = null;
			object totalPrice = null;
			object giftCouponUseAmount = null;
			object tax = null;
			object shippingCost = null;
			object finalAmount = null;
			object isPaymentClear = null;
			object trackingNumber = null;
			object orderStatus = null;

            for (int i = 0; i < conditions.Count; i++)
            {
                string fieldName = Utility.ToHungarianNotation(conditions[i].FieldName);

                if (conditions[i].JoiningCondition == JoinOperator.FirstValue)
                {
                    condition.Append("WHERE ");
                }
                else if (conditions[i].JoiningCondition == JoinOperator.And)
                {
                    condition.Append(" AND ");
                }
                else if (conditions[i].JoiningCondition == JoinOperator.Or)
                {
                    condition.Append(" OR ");
                }

                condition.Append(conditions[i].FieldName).Append(" ").Append(Condition.MapCondition(conditions[i].ConditionalOperator)).Append("@" + fieldName);

                if ((conditions[i].ConditionalOperator == ConditionOperator.Like ||
                    conditions[i].ConditionalOperator == ConditionOperator.NotLike))
                {
                    if (string.IsNullOrEmpty(conditions[i].Value.ToString()))
                        conditions[i].Value = "%%%";
                    else
                        conditions[i].Value = "%" + conditions[i].Value.ToString() + "%";
                }

                if (fieldName == TableColumns.Id.ToString())
                    id = conditions[i].Value;
                else if (fieldName == TableColumns.OrderedBySiteuserId.ToString())
					orderedBySiteuserId = conditions[i].Value;
				else if (fieldName == TableColumns.ItemProductId.ToString())
					itemProductId = conditions[i].Value;
				else if (fieldName == TableColumns.ItemQuantity.ToString())
					itemQuantity = conditions[i].Value;
				else if (fieldName == TableColumns.TotalPrice.ToString())
					totalPrice = conditions[i].Value;
				else if (fieldName == TableColumns.GiftCouponUseAmount.ToString())
					giftCouponUseAmount = conditions[i].Value;
				else if (fieldName == TableColumns.Tax.ToString())
					tax = conditions[i].Value;
				else if (fieldName == TableColumns.ShippingCost.ToString())
					shippingCost = conditions[i].Value;
				else if (fieldName == TableColumns.FinalAmount.ToString())
					finalAmount = conditions[i].Value;
				else if (fieldName == TableColumns.IsPaymentClear.ToString())
					isPaymentClear = conditions[i].Value;
				else if (fieldName == TableColumns.TrackingNumber.ToString())
					trackingNumber = conditions[i].Value;
				else if (fieldName == TableColumns.OrderStatus.ToString())
					orderStatus = conditions[i].Value;
            }

            AddCommandParameter(command, "@Condition", SqlDbType.NVarChar, 2000, ParameterDirection.Input, condition.ToString());
            AddCommandParameter(command, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, id);
			AddCommandParameter(command, "@OrderedBySiteuserId", SqlDbType.Int, 0, ParameterDirection.Input, orderedBySiteuserId);
			AddCommandParameter(command, "@ItemProductId", SqlDbType.Int, 0, ParameterDirection.Input, itemProductId);
			AddCommandParameter(command, "@ItemQuantity", SqlDbType.Int, 0, ParameterDirection.Input, itemQuantity);
			AddCommandParameter(command, "@TotalPrice", SqlDbType.Decimal, 0, ParameterDirection.Input, totalPrice);
			AddCommandParameter(command, "@GiftCouponUseAmount", SqlDbType.Decimal, 0, ParameterDirection.Input, giftCouponUseAmount);
			AddCommandParameter(command, "@Tax", SqlDbType.Decimal, 0, ParameterDirection.Input, tax);
			AddCommandParameter(command, "@ShippingCost", SqlDbType.Decimal, 0, ParameterDirection.Input, shippingCost);
			AddCommandParameter(command, "@FinalAmount", SqlDbType.Decimal, 0, ParameterDirection.Input, finalAmount);
			AddCommandParameter(command, "@IsPaymentClear", SqlDbType.Bit, 0, ParameterDirection.Input, isPaymentClear);
			AddCommandParameter(command, "@TrackingNumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, trackingNumber);
			AddCommandParameter(command, "@OrderStatus", SqlDbType.NVarChar, 250, ParameterDirection.Input, orderStatus);
        }

        /// <summary>
        /// Binds the fetched data from data reader to Objects
        /// </summary>
        /// <param name="reader">Data reader supplied by BaseDAO</param>
        /// <returns>List of object instances that was bound</returns>
        protected override List<BaseDAO> BindData(DbDataReader reader)
        {
            List<BaseDAO> result = new List<BaseDAO>();

			if (reader == null)
                return null;

            while (reader.Read())
            {
                SaleOrder saleOrder = new SaleOrder
                (
					reader["id"] == System.DBNull.Value ? GetIdMinValue : (int)reader["id"],
                    reader["ordered_by_siteuser_id"] == System.DBNull.Value ? 0 : (int)reader["ordered_by_siteuser_id"],
					reader["item_product_id"] == System.DBNull.Value ? 0 : (int)reader["item_product_id"],
					reader["item_quantity"] == System.DBNull.Value ? 0 : (int)reader["item_quantity"],
					reader["total_price"] == System.DBNull.Value ? 0.00 : (double)reader["total_price"],
					reader["gift_coupon_use_amount"] == System.DBNull.Value ? 0.00 : (double)reader["gift_coupon_use_amount"],
					reader["tax"] == System.DBNull.Value ? 0.00 : (double)reader["tax"],
					reader["shipping_cost"] == System.DBNull.Value ? 0.00 : (double)reader["shipping_cost"],
					reader["final_amount"] == System.DBNull.Value ? 0.00 : (double)reader["final_amount"],
					reader["is_payment_clear"] == System.DBNull.Value ? false : (bool)reader["is_payment_clear"],
					reader["tracking_number"] == System.DBNull.Value ? string.Empty : (string)reader["tracking_number"],
					reader["order_status"] == System.DBNull.Value ? string.Empty : (string)reader["order_status"]
                );

                result.Add(saleOrder);
            }
            
            if(!reader.IsClosed)
                reader.Close();

            return result;
        }

        /// <summary>
        /// List of store procedures that this class use
        /// </summary>
        private enum StoreProcedureName
        {
            Sp_SaleOrder_Save = 0,
            Sp_SaleOrder_Create = 1,
            Sp_SaleOrder_DeleteOne = 2,
            Sp_SaleOrder_DeleteMultiple = 3,
            Sp_SaleOrder_DeleteConditional = 4,
            Sp_SaleOrder_SaveConditional = 5,
            Sp_SaleOrder_LoadConditional = 6,
            Sp_SaleOrder_Load = 7,
            Sp_SaleOrder_LoadConditionalPaged = 8,
            Sp_SaleOrder_LoadConditionalPagedCount = 9,
            Sp_SaleOrder_LoadPaged = 10,
            Sp_SaleOrder_LoadPagedCount = 11
        }

        /// <summary>
        /// List of table column names that this class use
        /// </summary>
        private enum TableColumns
        {
            Id = 0,
			OrderedBySiteuserId = 1,
			ItemProductId = 2,
			ItemQuantity = 3,
			TotalPrice = 4,
			GiftCouponUseAmount = 5,
			Tax = 6,
			ShippingCost = 7,
			FinalAmount = 8,
			IsPaymentClear = 9,
			TrackingNumber = 10,
			OrderStatus = 11
        }
    }
}